package com.sk.waste.app.views;

import android.content.Context;
import android.util.AttributeSet;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

public class SKRecyclerView extends RecyclerView
  {
    private int SCROLLTYPE = 0;//0 横向滚动，1竖向滚动

    private Runnable autoPollTask = new Runnable()
      {
        @Override
        public void run()
          {
            LinearLayoutManager layoutManager = (LinearLayoutManager) getLayoutManager();
            int totalItemCount = layoutManager.getItemCount();
            int lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition();
            if (lastVisibleItemPosition + 1 == totalItemCount)
              {
                // 如果滚动到末尾，则重新从头开始滚动
                scrollToPosition(0);
                stopAutoScroll();
                startAutoScroll();
              } else
              {
                // 每次滚动固定的距离，实现从左向右滚动
                if (SCROLLTYPE == 0)
                  {
                    scrollBy(1, 0); // 参数1为水平滚动距离，正值表示向右滚动
                  } else
                  {
                    scrollBy(0, 1);
                  }
                postDelayed(this, 5); // 每10毫秒滚动一次
              }
          }
      };

    public SKRecyclerView(Context context)
      {
        super(context);
      }

    public SKRecyclerView(Context context, AttributeSet attrs)
      {
        super(context, attrs);
      }

    public void setScrollType(int type)
      {
        SCROLLTYPE = type;
      }

    public void startAutoScroll()
      {
        // 开始自动滚动
        removeCallbacks(autoPollTask); // 防止多次启动
        postDelayed(autoPollTask, 5);
      }

    public void stopAutoScroll()
      {
        // 停止自动滚动
        removeCallbacks(autoPollTask);
      }
  }
